package com.updata.up.controller;

import com.alibaba.fastjson.JSON;
import com.updata.up.eunm.FileUrlEnum;
import com.updata.up.utils.DateUtils;
import com.updata.up.utils.HttpSendUtil;
import com.updata.up.pojo.UpdataJson;
import com.updata.up.service.UpSaveService;
import com.updata.up.utils.jarFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/api")
public class UpdateController {

    @Autowired
    private UpSaveService upSaveService;


    //获取更新信息
    @RequestMapping(value = "/getUpdata", method = RequestMethod.POST)
    public String getUpdata() {
        try {
            String res = HttpSendUtil.getRequest(FileUrlEnum.updateUrl, "{\"ip\":\"1.1.1.1\"}");//updateUrl就是服务器上latest.json
            log.info("请求返回结果=", res);
            if (StringUtils.isNotBlank(res)) {
                UpdataJson updataJson = JSON.parseObject(res, UpdataJson.class);
                if (updataJson != null) {
                    log.error(updataJson.toString());
                    //获取本地版本号
                    String nowVersion = jarFileUtils.readJarFile(FileUrlEnum.LOCALVERSION);
                    //这里是从jar文件中读取META-INFO信息
                    log.error("META-INFO获取本地版本号内容是=" + nowVersion);
                    if (nowVersion != null) {
                        //对比版本，如果比当前大，就开始更新
                        if (Double.parseDouble(updataJson.getVersion()) <= Double.parseDouble(nowVersion)) {
                            log.error("当前版本：" + nowVersion + ",已经是最新版本");
                            return "\"当前版本：\" + nowVersion + \",已经是最新版本\"";
                        } else {
                            log.error("当前版本：" + nowVersion + ",不是最新的");
                            System.out.println("线上版本地址：" + updataJson.getPackageUrl());
                            //下载远程文件
                            String up = upSaveService.up(updataJson.getPackageUrl(), FileUrlEnum.filePath, updataJson.getFileName());
                            if (up.equals("ok")) {
                                System.out.println("保存成功=======");
                                return "保存成功";
                            } else {
                                System.out.println("保存失败==============");
                                return "保存失败";
                            }
                        }
                    } else {
                        log.error("读取META-INFO失败");
                    }
                }
            } else {
                log.error("更新文件不存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * 获取更新状态 并且重启项目
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getUpdataRestart", method = RequestMethod.POST)
    public String GetUpdataRestart() throws IOException {
        try {
            //重启
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("request_time", "1662532676192");
            map.add("data", "{\"project_name\":\"up-0\"}");
            map.add("request_token", "9b85c1e78bb72d51181dd37d6149f161");
            String s = HttpSendUtil.postRequests(FileUrlEnum.bt_Restart_Url, map);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
            return "重启失败";
        }
        return "重启成功";
    }

    /**
     * chongmingm
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/getRename", method = RequestMethod.POST)
    public String getRename(){
        try {
            //重启
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("request_time", "1662532676192");
            map.add("sfile", "/www/wwwroot/up-0.1.jar");
            map.add("dfile", "/www/wwwroot/up-0.1.jar.bak");
            map.add("request_token", "9b85c1e78bb72d51181dd37d6149f161");
            String s = HttpSendUtil.postRequests(FileUrlEnum.bt_Rename_Url, map);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
            return "重命名失败";
        }
        return "重命名成功";
    }

    /**
     * 获取进度
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/getUpdataSchedule")
    public String getUpdataSchedule() {
        return String.format("%.2f", (upSaveService.sumLen / upSaveService.fileSize) * 100);
    }

//    @RequestMapping("/gets")
//    public String downloadNets()   {
//        return "有次井口";
//    }


}
